import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
const initialState: CounterStore.InitialState = {
  count: 0,
}
const counterStore = createSlice({
  name: 'counter',
  // 初始化state
  initialState: initialState,
  //   修改方法 同步方法 支持直接修改
  reducers: {
    increase(state) {
      state.count++
    },
    decrease(state) {
      state.count--
    },
    setCount(state, action: PayloadAction<number>) {
      state.count = action.payload
    },
  },
  extraReducers: (builder) => {
    builder.addCase(addAmountAsync.fulfilled, (state, { payload }) => {
      state.count += payload
    })
  },
})

// 异步方法
export const addAmountAsync = createAsyncThunk('incrementAsync', async () => {
  // 返回一个Promise对象，Promise对象的结果类型为number
  const res = await new Promise<number>((resolve) => {
    setTimeout(() => {
      resolve(3)
    }, 3000)
  })
  return res
})
// 异步方法1
export const addAmountAsync1 = () => {
  return async (dispatch: AppDispatch) => {
    const res = await new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(3)
      }, 3000)
    })
    dispatch(setCount(res))
  }
}
// 结构出actionCreater 函数 需导出actionCreate
export const { increase, decrease, setCount } = counterStore.actions
// 获取reducer 默认导出reducer
const reducer = counterStore.reducer
export default reducer
